package com.aynu.account.handler;

import com.baidu.aip.util.Base64Util;
import com.aynu.account.tools.HttpUtil;
import com.aynu.account.tools.ImageUrlTools;
import com.aynu.commons.ai.AiParam;
import com.aynu.commons.ai.BaiduAIHelper;
import com.aynu.modules.po.VehiclePO;
import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

@Component
public class AiHelper {
    @Value("${baidu.apikey}")
    private String API_KEY;
    @Value("${baidu.secretkey}")
    private String SECRET_KEY;

    private final static Logger logger = LoggerFactory.getLogger(AiHelper.class);

    final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    /*

    图像识别，获取车牌信息
    文档（行驶证识别）：https://cloud.baidu.com/doc/OCR/s/yk3h7y3ks
    文档（车牌识别）：https://cloud.baidu.com/doc/OCR/s/ck3h7y191
    获取车辆照片url
    将url下载到某个临时文件夹
    将文件编码为base64
    调百度AI接口，返回对应信息
    对比：行驶证车牌 和 车辆车牌是否一致
    如果一致，设置车牌信息，认证通过，身份变更为车主

    简化版业务流程（至少完成）：识别车辆车牌号即可

    * */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private ImageUrlTools imageTool;
    //构建百度ai帮助工具

    public String getLicense(VehiclePO vehiclePO) throws Exception {
        String url="https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate";
        return getPlateNumber(vehiclePO.getCarFrontPhoto(),vehiclePO.getId(),url,"number","words_result.number");

//        AIResult licensePlateMap = baiduAIHelper.getLicensePlateMap(ImageUrlTools.getRemoteUrl(vehiclePO.getCarFrontPhoto()));
        //返回识别结果，默认不开启多车牌识别，测试得知车牌号的key为card_number
//        return licensePlateMap.getParameter("card_number");
    }
    public String getBackNumber(VehiclePO vehiclePO) throws Exception {
        String url="https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license";
        return getPlateNumber(vehiclePO.getCarBackPhoto(), vehiclePO.getId(), url,"words","words_result.号牌号码.words");
    }

    @NotNull
    private static String getImgParam(File imgFile) throws IOException {
        byte[] imgData = FileUtils.readFileToByteArray(imgFile);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "utf-8");
        return "image="+imgParam;
    }

    public String getPlateNumber(String imgUrl,String imgName,String requestURL,String name,String filed) throws Exception {
        BaiduAIHelper baiduAIHelper=new BaiduAIHelper(API_KEY,SECRET_KEY,redisTemplate);
        //下载图片到暂存目录
        File imgFile = imageTool.downloadImage(imgUrl,imgName+System.currentTimeMillis()+".jpg" );
        String param=getImgParam(imgFile);
        String accessToken = baiduAIHelper.getAccessToken();
        String res=HttpUtil.post(requestURL,accessToken,param);
        List<AiParam> aiParams = new ArrayList<>();
        aiParams.add(new AiParam(name,filed));
        List<AiParam> result = baiduAIHelper.parseData(res, aiParams);
        //删除临时文件
        Files.delete(imgFile.toPath());
        logger.info("Cache image deleted {}",imgFile);
        return result.get(0).getValue();
    }
}
